'use strict';
const db = uniCloud.database();
const UniID = require('uni-id-common');

exports.main = async (event, context) => {
  let body = event;
  if (event.body !== undefined) {
    try {
      body = JSON.parse(event.body);
    } catch (e) {
      return {
        success: false,
        message: '请求体 JSON 解析失败',
        error: e.message
      };
    }
  }

  const { uniIdToken, days = 7 } = body;

  // 校验 days
  if (!Number.isInteger(days) || days <= 0) {
    return {
      success: false,
      message: '参数 days 必须为大于 0 的整数'
    };
  }

  if (!uniIdToken) {
    return {
      success: false,
      message: '缺少 uniIdToken'
    };
  }

  const uniID = UniID.createInstance({ context });

  // 验证 token 并获取用户信息
  const tokenRes = await uniID.checkToken(uniIdToken);
  if (tokenRes.code !== 0 || !tokenRes.uid) {
    return {
      success: false,
      message: 'Token 无效或已过期'
    };
  }

  const consultant_id = tokenRes.uid;

  try {
    const labels = [];
    const dateMap = {};
    
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const yesterday = new Date(today.getTime() - 1 * 24 * 60 * 60 * 1000);
    
    const targetDays = [];
    for (let i = days; i >= 1; i--) {
      const date = new Date(yesterday.getTime() - (i - 1) * 24 * 60 * 60 * 1000);
      const dayStr = date.toISOString().slice(0, 10); // YYYY-MM-DD
      const label = `${('0' + (date.getMonth() + 1)).slice(-2)}/${('0' + date.getDate()).slice(-2)}`;
      labels.push(label);
      dateMap[dayStr] = 0;
      targetDays.push(dayStr);
    }
	
	const res = await db.collection('appoint_records')
	  .where({
		day: db.command.in(targetDays),
		consultant:consultant_id
	  })
	  .get();
	console.log(res,targetDays,consultant_id)
	
    res.data.forEach(item => {
      const dateStr = item.day;
      if (typeof dateStr !== 'string') {
        console.warn('day 非字符串类型:', dateStr);
        return;
      }
      if (dateMap.hasOwnProperty(dateStr)) {
        dateMap[dateStr]++;
      }
    });

    // 将统计结果返回
    const data = Object.values(dateMap);

    return {
      success: true,
      result: {
        labels,
        data
      }
    };

  } catch (error) {
    console.error('图表数据查询失败:', error);
    return {
      success: false,
      message: '查询失败',
      error: error.message
    };
  }
};
